<template>
  <div class="infoConfig">
    <el-form ref="form" :model="form" :rules="rules">
      <div class="leftLine title">机构信息</div>
      <el-row class="plugContent">
        <el-col :span="5">机构</el-col>
        <el-col :span="7">{{ form.orgName }}</el-col>
        <el-col :span="5">业务编号</el-col>
        <el-col :span="7">{{ form.orgId }}</el-col>
      </el-row>
      <div class="leftLine title">
        直属上级抽佣占比
      </div>
      <el-form-item label="" prop="agtList" class="plugContent">
        <AddList v-model="form.agtList" :show-add-btn="false" :show-del-btn="false">
          <template v-slot="{item: { item, index }}">
            <div v-if="pageType == 'detail'">
              <span class="mg-r-20 formItemLabel">{{ item.name }}</span>
              <span class="mg-r-20">
                抽取直属商户插件佣金的{{ form[item.key] }}%
                <span v-show="item.key == 'orgRate'">
                  <span v-if="form[item.key] != 100">平台可得插件佣金{{ 100 - form[item.key] }}%</span>
                  <span v-else>平台不抽佣</span>
                </span>
              </span>
            </div>
            <div v-else-if="['edit', 'add'].includes(pageType)">
              <span class="mg-r-20 formItemLabel">{{ item.name }}</span>
              <span class="mg-r-20">抽取直属商户插件佣金的
                <el-input-number v-model="form[item.key]" :controls="false" class="numInput" size="small" :step="1" :precision="0" :min="0" :max="100" />%
                <span v-show="item.key == 'orgRate'">
                  <span v-if="form[item.key] != 100">平台可得插件佣金{{ 100 - form[item.key] }}%</span>
                  <span v-else>平台不抽佣</span>
                </span>
              </span>
            </div>
          </template>
        </AddList>
      </el-form-item>
      <!-- 插件列表 -->
      <components
        :is="plugs[plug.pluginCode] || 'basePlugTem'"
        v-for="(plug,index) of form.orgPluginConfs"
        :key="plug.pluginCode"
        :ref="plug.pluginCode"
        :form="plug"
        :index="index + 1"
        :all-data="form"
        :page-type="pageType"
      />
      <div v-if="['edit', 'add'].includes(pageType)" class="btnList textCenter">
        <el-button size="small" @click="$emit('close')">取消</el-button>
        <el-button type="primary" size="small" @click="submit">保存配置</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import AddList from '@/components/AddList/index.vue'
import plugs from './components/plugs'
import { update } from '@/api/flowConf'

import { pluginConfUpdate, pluginConfAdd } from '@/api/plugs'
export default {
  components: { AddList, ...plugs },
  props: {
    infoConfig: {}
  },
  data() {
    return {
      plugs,
      text: '',
      form: {},
      rules: {
        orgDiscountConf: [{ validator: this.valid, trigger: ['change', 'blur'] }],
        agtList: [{ validator: this.valid, trigger: ['change', 'blur'] }],
        agtConfigList: [{ validator: this.valid, trigger: ['change', 'blur'] }],
        mercConfigList: [{ validator: this.valid, trigger: ['change', 'blur'] }],
        // flowRatio: [{ validator: this.valid, trigger: ['change','blur'] }],
        interactionRatio: [{ validator: this.valid, trigger: ['change', 'blur'] }]
      }
    }
  },
  computed: {
    pageType() { return this.infoConfig.type }
  },
  mounted() {
    this.initData()
    console.log('plugs', this.plugs)
  },
  methods: {
    initData() {
      console.log('this.infoConfig ', this.infoConfig)
      const baseData = JSON.parse(JSON.stringify(this.infoConfig.data))
      const { orgPluginConfs, plugConfList } = baseData
      const _orgPlugs = orgPluginConfs ? JSON.parse(JSON.stringify(orgPluginConfs)) : []
      // 配置中刚开启的插件列表 在详情中查不到  需要组合配置
      if (_orgPlugs && plugConfList && plugConfList.length) {
        plugConfList.forEach(plug => {
          const { isOpen, code, name } = plug
          // 详情中插件列表 是否已经含有该插件
          const hasPlug = _orgPlugs.some(orgPlug => orgPlug.pluginCode == code)
          // 如果配置插件列表中该插件已打开  但是详情插件列表中没有该插件
          if (isOpen && !hasPlug) {
            _orgPlugs.push({
              'pluginCode': code,
              'pluginName': name,
              'pluginSpecialConfs': [{ isAddYear: 0 }]
            })
          }
        })
      }
      this.form = {
        ...baseData,
        orgPluginConfs: _orgPlugs,
        agtList: [
          { name: '租户', key: 'orgRate' },
          { name: '运营中心', key: 'operCenterRate' },
          { name: '一级代理', key: 'oneAgtRate' },
          { name: '二级代理', key: 'twoAgtRate' },
          { name: '三级代理', key: 'threeAgtRate' }
        ]
        // mercConfigList: baseData.orgPackageConf.filter(v => v.roleType == 2),
        // agtConfigList: baseData.orgPackageConf.filter(v => v.roleType == 1)
      }
      console.log('this.form', this.form)
    },
    submit() {
      this.$refs['form'].validate((valid) => {
        if (valid && this.validForm()) {
          const obj = {
            ...this.form
          }
          const _fun = this.pageType == 'edit' ? pluginConfUpdate : pluginConfAdd
          _fun(obj).then(res => {
            this.$message.success('操作成功！')
            this.$emit('sucClose')
          })
        } else {
          this.$message.error('表单信息填写有误，请重新检查！')
          return false
        }
      })
    },
    // 校验插件信息是否填写完成
    validForm() {
      let validRes = true
      this.form.orgPluginConfs.forEach(plug => {
        console.log('this.$refs[plug]', this.$refs[plug.pluginCode])
        const refItem = this.$refs[plug.pluginCode][0]
        refItem.$refs.form.validate((valid) => {
          if (!valid) validRes = false
        })
      })
      return validRes
    },
    valid(rule, value, callback) {
      const { field } = rule
      let text = ''
      switch (field) {
        case 'orgDiscountConf': {
          // 租户流量余额折扣配置
          if (this.form.orgDiscountConf.length) {
            this.form.orgDiscountConf.forEach((item, index) => {
              if (!item.singlePay || !item.discount) {
                text += `配置${index + 1}信息不完整 `
              }
            })
          } else {
            text = '至少填写一条配置'
          }
          text ? callback(text) : callback()
          break
        }
        case 'agtList': {
          // 代理流量余额折扣配置
          // this.form.agtList.forEach(item => {
          //   const _data = this.form[item.key]
          //   if (!_data && _data != 0) {
          //     text += `请输入${item.name}抽佣占比 `
          //   }
          // })
          this.form.agtList.reduce((prev, now) => {
            if (prev.key) {
              const { key: prevKey, name: prevName } = prev
              const { key: nowKey, name: nowName } = now
              if (!this.form[nowKey] && this.form[nowKey] != 0) {
                text += `请输入${nowName}抽佣占比 `
              } else if (this.form[prevKey] < this.form[nowKey]) {
                text += `${prevName}: 请输入${this.form[nowKey]}-100的整数 `
              }
            }
            return now
          }, {})
          text ? callback(text) : callback()
          break
        }
        case 'agtConfigList': {
          // 代理套餐配置
          if (this.form.agtConfigList.length) {
            this.form.agtConfigList.forEach((item, index) => {
              if (!item.rechargeFixMoney) {
                text += `配置${index + 1}信息不完整 `
              }
            })
          } else {
            text = '请配置 代理套餐配置'
          }
          text ? callback(text) : callback()
          break
        }
        case 'mercConfigList': {
          // 代理套餐配置
          if (this.form.mercConfigList.length) {
            this.form.mercConfigList.forEach((item, index) => {
              if (!item.rechargeFixMoney) {
                text += `配置${index + 1}信息不完整 `
              }
            })
          } else {
            text = '请配置 商户开户门槛&充值金额配置'
          }
          text ? callback(text) : callback()
          break
        }
        // case 'flowRatio': {
        //   // 流量标准资费
        //   if (!this.form.flowRatio) {
        //     text = '请配置 流量标准资费'
        //   }
        //   text ? callback(text) : callback()
        //   break
        // }
        case 'interactionRatio': {
          // 流量兑换交互次数比例
          if (!this.form.interactionRatio) {
            text = '请配置 流量兑换交互次数比例'
          }
          text ? callback(text) : callback()
          break
        }
        default:
          break
      }
    },
    addLine(type) {
      switch (type) {
        case 'orgDiscountConf':
          this.form.orgDiscountConf.push({
            singlePay: 0,
            discount: 1,
            'orgId': this.form.orgId
          })
          break
        case 'agtConfigList':
          this.form.agtConfigList.push({
            rechargeFixMoney: 1,
            roleType: 1,
            'orgId': this.form.orgId
          })
          break
        case 'mercConfigList':
          this.form.mercConfigList.push({
            rechargeFixMoney: 1,
            roleType: 2,
            'orgId': this.form.orgId
          })
          break
        default:
          break
      }
    }
  }

}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.infoConfig{
  padding: 30px;
  .title,
  /deep/.title{
    font-size: 15px;
    color: #000;
    margin: 30px 0;
  }
  .numInput,
  /deep/.numInput{
    width: 100px;
    margin: 0 10px;
  }
  /deep/.formBox,
  .formBox{
    display: flex;
    .formItemLabel{
      flex-shrink: 0;
    }
    .formItemValue{
      flex: 1;
    }
  }
  /deep/.formItemLabel,
  .formItemLabel{
    width: 100px;
    display: inline-block;
    vertical-align: top;
  }

  .plugContent,
  /deep/.plugContent{
    padding-left: 30px;
  }

}
</style>
